package my.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Page;
import my.common.Util;
import my.interceptor.CategoryMenuInterceptor;
import my.interceptor.Login;
import my.model.Message;
import my.model.User;
import my.service.MessageService;

/**
 * Created by Administrator on 2017/4/13 0013.
 */
public class MessageController extends Controller {

    MessageService messageService = new MessageService();

    @Before(CategoryMenuInterceptor.class)
    public void index() {
        list();

    }

    @Before(CategoryMenuInterceptor.class)
    public void list() {

        renderFreeMarker("list.ftl");

    }


    public void json() {
        int draw = getParaToInt("draw", 1);
        int length = getParaToInt("length", 10);
        int start = getParaToInt("start", 0);

        int page = start / length + 1;

        Page<Message> messagePage = messageService.paginateAllMessageDetail(page, length);
        setAttr("data", messagePage.getList());
        setAttr("draw", draw);
        setAttr("recordsTotal", messagePage.getTotalRow());  //获得总记录数
        setAttr("recordsFiltered", messagePage.getTotalRow());  //获得总记录数

        renderJson();

        //messageService.paginateAllMessageDetail()
        //   setAttr("messages",messages);
        //renderJson(messages);
    }


    @Before({Login.class, POST.class})
    public void update() {
        Message message = getModel(Message.class, "", true);
        Message findMessage = messageService.getMessageById(message.getId());
        User loginUser = getSessionAttr("user");
        boolean success = false;
        String retMessage = null;
        if (findMessage.getUserId() == loginUser.getId()) {  //说明是发表留言的用户 可以编辑
            success = messageService.updateMessage(message);
        }
        retMessage = success ? "编辑成功" : "编辑失败";
        renderJson(Util.ajaxJson(success, retMessage));

    }

    @Before({Login.class, POST.class})
    public void delete() {

        User loginUser = (User) getSessionAttr("user");
        int id = getParaToInt(0, -1);

        boolean success = messageService.deleteMessageById(loginUser.getId(), id);


        renderJson(Util.ajaxJson(success, success ? "删除成功" : "删除失败"));
        //list();
    }


    public void create() {
        //TODO:显示发表留言页面 要求登录后才能留言
        // 提示 @Before(Login.class) 使用拦截器
        renderFreeMarker("create.ftl");
    }

    @Before({Login.class, POST.class})
    public void save() {
        Message message = getModel(Message.class, "", true);
        boolean success = messageService.saveMessage(message);
        renderJson(Util.ajaxJson(success, success ? "留言成功" : "留言失败"));
    }


}
